package com.bookingService;

import java.io.File;
import java.util.List;

import javax.xml.XMLConstants;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;

import org.xml.sax.SAXException;

public class BookingService {
	
	public static void main(String[] args) {
		List<Booking> bookingList=getBookingList();
		saveBookingList(bookingList);
	}
	
	public static List<Booking> getBookingList(){
		try{
			JAXBContext jaxbContext=JAXBContext.newInstance(BookingList.class);
			Unmarshaller jaxbUnmarshaller=jaxbContext.createUnmarshaller();
			Schema schema;
			SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			schema=schemaFactory.newSchema(new File("BookingListSchema.xsd"));
			jaxbUnmarshaller.setSchema(schema);
			BookingList bl=(BookingList)jaxbUnmarshaller.unmarshal(new File("BookingList.xml"));
			return bl.getBooking();
		}catch(JAXBException e){
			System.err.println(e);
		}catch(SAXException e){
			System.err.println(e);
		}
		return null;
	}
	
	public static void saveBookingList(List<Booking> bookingList){
		try{
			BookingList bl=new BookingList();
			bl.setBooking(bookingList);
			
			File file=new File("BookingList.xml");
			JAXBContext jaxbContext=JAXBContext.newInstance(BookingList.class);
			Marshaller jaxbMarshaller=jaxbContext.createMarshaller();
			Schema schema;
			SchemaFactory schemaFactory=SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
			schema=schemaFactory.newSchema(new File("BookingListSchema.xsd"));
			jaxbMarshaller.setSchema(schema);
			jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
			jaxbMarshaller.marshal(bl, file);
		}catch(JAXBException e){
			System.err.println(e);
		}catch(SAXException e){
			System.err.println(e);
		}
	}

}
